﻿using System.Text.Json;
using ZYXmeBase.Contracts;

namespace ZYXmeBase.Middleware
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            this.next = next;
            _logger = logger;
        }

        /// <summary>
        /// Invoke
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
                var features = context.Features;
            }
            catch (Exception ex)
            {
                await ExceptionHandlerAsync(context, ex);
            }
        }

        /// <summary> 
        /// 异常处理，返回JSON
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <returns></returns>

        private async Task ExceptionHandlerAsync(HttpContext context, Exception e)
        {
            context.Response.ContentType = "text/json;charset=utf-8;";
            var errorMessage = "";
            var result = new ApiResponse();
            if (e is BusinessException exception)
            {
                context.Response.StatusCode = exception.StatusCode;
                errorMessage = exception.Message;
                _logger.LogError(exception.Message);
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status200OK;
                errorMessage = e.Message;
                //if (_environment.IsDevelopment() || _environment.IsStaging())
                //{
                //    errorMessage = e.Message;
                //}
                //else
                //{
                //    errorMessage = "服务器异常，请稍后重试";
                //}
                _logger.LogError("未捕捉的异常，异常消息:" + e.Message + "\r 异常堆栈:" + e.StackTrace);
                var innerException = e.InnerException;
                while (innerException != null)
                {
                    _logger.LogError("内部异常消息:" + innerException.Message);
                    _logger.LogError("内部异常堆栈:" + innerException.StackTrace);
                    innerException = innerException.InnerException;
                }
            }
            result.IsFailed(errorMessage);
            await context.Response.WriteAsJsonAsync(result, new JsonSerializerOptions
            {
                PropertyNamingPolicy = null
            });
        }
    }

}
